Philosophy of [WebInvoke(ResponseFormat = WebMessageFormat.Json)]

Posted by Mikey Cee on Stack Overflow See other posts from Stack Overflow or by Mikey Cee
Published on 2010-05-26T15:57:38Z Indexed on 2010/05/26 16:01 UTC
Read the original article Hit count: 989

Filed under:
|

Hi everyone,

I'm writing what I'm referring to as a POJ (Plain Old JSON) WCF web service - one that takes and emits standard JSON with none of the crap that ASP.NET Ajax likes to add to it.

It seems that there are three steps to accomplish this:

  1. Change to in the endpoint's tag
  2. Decorate the method with [WebInvoke(ResponseFormat = WebMessageFormat.Json)]
  3. Add an incantation of [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] to the service contract

This is all working OK for me - I can pass in and am being returned nice plain JSON.

If I remove the WebInvoke attribute, then I get XML returned instead, so it is certainly doing what it is supposed to do. But it strikes me as odd that the option to specify JSON output appears here and not in the configuration file. Say I wanted to expose my method as an XML endpoint too - how would I do this? Currently the only way I can see would be to have a second method that does exactly the same thing but does not have WebMethodFormat.Json specified. Then rinse and repeat for every method in my service? Yuck.

Specifying that the output should be serialized to JSON in the attribute seems to be completely contrary to the philosophy of WCF, where the service is implemented is a transport and encoding agnostic manner, leaving the nasty details of how the data will be moved around to the configuration file.

Is there a better way of doing what I want to do? Or are we stuck with this awkward attribute? Or do I not understanding WCF deeply enough?

© Stack Overflow or respective owner

Related posts about wcf

Related posts about JSON